package com.ex.net;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import com.ex.util.LogUtil;
import com.example.androiddemo.Const;

/**
 * 文件下载
 * @author admin
 *
 */
public class DownloadUtil {
	
	/**
	 * HttpClient 下载文件
	 * @param url
	 */
	public static String clientDownload(String url) {
		String result = "";
		DefaultHttpClient client = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(url);
		
		try {
			HttpResponse response = client.execute(httpPost);
			if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				//将返回内容写入文件
				writeToFile(response.getEntity().getContent(), Const.SDCARD_PATH + File.separator + "downFile.txt");
				result = "下载完成";
			}
		} catch (ClientProtocolException e) {
			result = "下载发生异常";
			e.printStackTrace();
		} catch (IOException e) {
			result = "下载发生异常";
			e.printStackTrace();
		}
		
		return result;
		
	}
	
	/**
	 * java.net中的 HttpUrlConnection 类下载
	 * @param url ： 下载地址
	 */
	public static String httpUrlConnDownload(String urlPath) {
		String result = "初始化";
		try {
			URL url = new URL(urlPath);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("POST");
			connection.setConnectTimeout(6 * 10000);
			connection.setDoInput(true);
			
			int resCode = connection.getResponseCode();
			if(resCode == HttpURLConnection.HTTP_OK) {
				writeToFile(connection.getInputStream(), Const.SDCARD_PATH + File.separator + "aDownFile.txt");
			}
			result = "下载完成";
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
			result = "下载异常";
		} catch (IOException e) {
			e.printStackTrace();
			result = "下载异常";
		}
		return result;
		
	}
	
	private static void writeToFile(InputStream inputStream, String outPath) {
		try {
			FileOutputStream fileOutputStream = new FileOutputStream(outPath);
			byte[] buf = new byte[1024];
			while (inputStream.read(buf) != -1) {
				fileOutputStream.write(buf, 0, buf.length);
			}
			fileOutputStream.flush();
			fileOutputStream.close();
			inputStream.close();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
//		Toast.makeText(App.instance(), "下载完成", Toast.LENGTH_LONG).show();
		LogUtil.log("下载完成");
	}

}
